package com.michale.framework.security.service.impl;

import com.michale.common.constants.CommonConstant;
import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.properties.TokenProperties;
import com.michale.common.utils.Date.DateUtils;
import com.michale.common.utils.Ip.AddressUtils;
import com.michale.common.utils.Ip.IpUtils;
import com.michale.common.utils.Ip.ServletUtils;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.common.utils.uuid.IdUtils;
import com.michale.framework.security.service.TokenService;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Michale
 * @apiNote Token服务类
 */
@Slf4j
@Component
public class TokenServiceImpl implements TokenService {

    @Resource
    private TokenProperties tokenProperties;

    @Resource
    private RedisUtils redisUtils;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


    /**
     * 从数据生成令牌
     *
     * @param claims 数据
     * @return token
     */
    public String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, tokenProperties.getSecret())
                .compact();
    }

    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @return 数据声明
     */
    @Override
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(tokenProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 从请求中获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserDetail getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(CommonConstant.LOGIN_USER_KEY);
                return redisUtils.getCacheObject(getTokenKey(uuid));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUserDetail 用户信息
     */
    public void verifyToken(LoginUserDetail loginUserDetail) {
        long expireTime = loginUserDetail.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUserDetail);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUserDetail 用户信息
     */
    public void refreshToken(LoginUserDetail loginUserDetail) {
        loginUserDetail.setLoginTime(DateUtils.getNowDate());
        long time = loginUserDetail.getLoginTime().getTime();
        loginUserDetail.setExpireTime(time + tokenProperties.getExpireTime() * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUserDetail.getToken());
        redisUtils.setCacheObject(userKey, loginUserDetail, tokenProperties.getExpireTime(), TimeUnit.MINUTES);
    }

    /**
     * 创建令牌
     *
     * @param loginUserDetail 用户信息
     * @return 令牌
     */
    public String createToken(LoginUserDetail loginUserDetail) {
        String uuid = IdUtils.fastUUID();
        loginUserDetail.setToken(uuid);
        setUserAgent(loginUserDetail);
        refreshToken(loginUserDetail);
        Map<String, Object> claims = new HashMap<>();
        claims.put(CommonConstant.LOGIN_USER_KEY, uuid);
        return createToken(claims);
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUserDetail loginUserDetail) {
        if (StringUtils.isNotNull(loginUserDetail) && StringUtils.isNotEmpty(loginUserDetail.getToken())) {
            refreshToken(loginUserDetail);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void deleteLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtils.deleteObject(userKey);
        }
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUserDetail 登录信息
     */
    public void setUserAgent(LoginUserDetail loginUserDetail) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddress(ServletUtils.getRequest());
        loginUserDetail.setIpAddress(ip);
        loginUserDetail.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUserDetail.setBrowser(userAgent.getBrowser().getName());
        loginUserDetail.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从请求中获取token
     *
     * @param request 请求域
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(tokenProperties.getHeader());
        if (StringUtils.isNotEmpty(token) && token.startsWith(CommonConstant.TOKEN_PREFIX)) {
            token = token.replace(CommonConstant.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 获取缓存的token键值
     *
     * @param uuid 唯一标识
     * @return 缓存的token键值
     */
    public String getTokenKey(String uuid) {
        return RedisCacheConstant.LOGIN_TOKEN_KEY + uuid;
    }
}
